package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private MenuDao menuDao;

    @Override
    public User findByUsername(String username) {

        // 获取User
        User user = userDao.findByUsername(username);
        if(user == null){
            return null;
        }

        // 获取Role
        Integer userId = user.getId();
        Set<Role> roles = roleDao.findByUserId(userId);

        // 获取Permission
        if(roles != null && roles.size() > 0){
            for(Role role : roles){
                Integer roleId = role.getId();
                Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                if(permissions != null && permissions.size() > 0){
                    role.setPermissions(permissions);
                }
            }
            user.setRoles(roles);
        }

        return user;
    }

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<User> page = userDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void add(User user, Integer[] roleIds) {
        userDao.add(user);
        setUserAndRoleIds(user.getId(),roleIds);
    }

    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public List<Integer> findRoleIdsByUserId(Integer id) {
        return userDao.findRoleIdsByUserId(id);
    }
    //编辑检查组，同时需要更新和检查项的关联关系
    @Override
    public void edit(User user, Integer[] roleIds) {
        //根据检查组id删除中间表数据（清理原有关联关系）
        userDao.deleteAssociation(user.getId());
        //更新用户基本信息
        userDao.edit(user);
        //向中间表(t_user_role)插入数据（建立检查组和检查项关联关系）
        setUserAndRoleIds(user.getId(), roleIds);

    }

    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }

    @Override
    public void delete(Integer id) {
        userDao.deleteAssocication(id);
        userDao.delete(id);
    }

    private void setUserAndRoleIds(Integer userId, Integer[] roleIds) {
        if(roleIds != null && roleIds.length > 0){
            for (Integer roleId : roleIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("userid", userId);
                map.put("roleid", roleId);
                userDao.setUserAndRoleIds(map);
            }
        }
    }
	
	@Override
    public LinkedHashSet<Map<String, Object>> findMenusByUsername(String username) {
        User user = userDao.findByUsername(username);
        if(user == null){
            return null;
        }
        // 获取Role
        Integer userId = user.getId();
        Set<Role> roles = roleDao.findByUserId(userId);

        LinkedHashSet<Map<String, Object>> set = new LinkedHashSet<>();

        if(roles != null && roles.size() > 0){
            for (Role role : roles) {
                LinkedHashSet<Menu> menus = menuDao.findByRoleId(role.getId());
                if(menus != null && menus.size() > 0){
                    for (Menu menu : menus) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("path", menu.getPath());
                        map.put("title", menu.getName());
                        map.put("icon", menu.getIcon());
                        List<Menu> childrenMenus = menu.getChildren();
                        List<Map<String, Object>> childrenList = new ArrayList<>();
                        if(childrenMenus != null && childrenMenus.size() > 0){
                            for (Menu childrenMenu : childrenMenus) {
                                Map<String, Object> map1 = new HashMap<>();
                                map1.put("path", childrenMenu.getPath());
                                map1.put("title", childrenMenu.getName());
                                map1.put("icon", childrenMenu.getIcon());
                                map1.put("linkUrl", childrenMenu.getLinkUrl());
                                childrenList.add(map1);
                            }
                        }
                        map.put("children", childrenList);
                        set.add(map);
                    }
                }
            }
        }
        return set;
    }
}